package com.then.component.club.repository;


import android.arch.lifecycle.LiveData;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.luojilab.componentservice.prefs.Preferences;
import com.then.architecture.AppExecutors;
import com.then.architecture.data.api.ApiResponse;
import com.then.architecture.data.dto.Resource;
import com.then.architecture.data.repository.BaseRepository;
import com.then.architecture.data.repository.BoundResource;
import com.then.architecture.di.AppScope;
import com.then.component.club.api.RemoteService;
import com.then.component.club.db.ClubDao;
import com.then.component.club.dto.ClubListResponse;
import com.then.component.club.entity.Club;
import com.then.component.club.request.ClubListReq;

import java.util.List;

import javax.inject.Inject;

/**
 * Created by 42524 on 2018/1/29.
 */
@AppScope
public class ClubRepository extends BaseRepository<RemoteService> {


    ClubDao clubDao;

    Preferences preferences;

    @Inject
    ClubRepository(AppExecutors appExecutors, RemoteService remoteService, ClubDao clubDao, Preferences preferences) {
        super(appExecutors, remoteService);
        this.clubDao = clubDao;
        this.preferences = preferences;
    }


    public LiveData<Resource<List<Club>>> getClubList(ClubListReq req) {
        return new BoundResource<List<Club>, ClubListResponse>(appExecutors) {

            @Override
            protected void saveCallResult(@NonNull ClubListResponse item) {
                if (item.data.list != null) {
                    for (Club club : item.data.list) {
                        club.tLoginUserId = preferences.getUserId();
                    }
                }
                clubDao.insert(item.data.list);
            }

            @Override
            protected boolean shouldFetch(@Nullable List<Club> data) {
                return data == null || data.size() <= 0;
            }

            @NonNull
            @Override
            protected LiveData<List<Club>> loadFromDb() {
                return clubDao.load(preferences.getUserId());
            }

            @NonNull
            @Override
            protected LiveData<ApiResponse<ClubListResponse>> createCall() {
                return remoteService.getClubList(req.toMap());
            }
        }.asLiveData();
    }


}
